package com.kuanter.kuanterauto.userlogin;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import com.kuanter.kuanterauto.HomeActivityGroup;
import com.kuanter.kuanterauto.MainActivity;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.UserInfo;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;

/**
 * 用户登录 界面
 * 
 * @author soup
 * 
 */
@SuppressLint("HandlerLeak")
public class UserLoginActivity extends BaseActivity_NoBar {

	public static boolean isLogin = false;// 是否登录

	private EditText et_pnum_login = null;// 手机号
	private EditText et_psd_login = null;// 密码
	private Button bt_longin = null;// 登录按钮
	private Button bt_wjmm_longin = null;// 忘记密码按钮
	private Button btTopLeft_login = null;

	private String mobileNumber = "";
	private String userPassword = "";

	private DataReceiver dataReceiver = null;

	public static String startAction = "";

	DataLoader dataLoader = null;

	// private HttpTask task=null;
	InputMethodManager m = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.userlogin);
		// setTitle(R.drawable.userlogin);
		startAction = getIntent().getAction();

		initView();
		initListener();
		m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		m.toggleSoftInput(InputMethodManager.SHOW_FORCED,
				InputMethodManager.HIDE_IMPLICIT_ONLY);
		// 注册广播
		register_Receiver();

		dataLoader = new DataLoader(this);
	}

	private void initView() {
		et_pnum_login = (EditText) findViewById(R.id.et_pnum_login);
		et_psd_login = (EditText) findViewById(R.id.et_psd_login);
		bt_longin = (Button) findViewById(R.id.bt_longin);
		bt_wjmm_longin = (Button) findViewById(R.id.bt_wjmm_longin);
		btTopLeft_login = (Button) findViewById(R.id.btTopLeft_login);

//		 et_pnum_login.setText("15623090030");
//		 et_psd_login.setText("123123");
		
//		et_pnum_login.setText("13164183954");
//		et_psd_login.setText("123456");
	}

	private void initListener() {
		bt_longin.setOnClickListener(this);
		bt_wjmm_longin.setOnClickListener(this);
		btTopLeft_login.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btTopLeft_login:
			m.hideSoftInputFromWindow(et_pnum_login.getWindowToken(), 0);
			m.hideSoftInputFromWindow(et_pnum_login.getWindowToken(), 0);
			isLogin = false;
			if (startAction.equals(MainConstants.SZ_ACTION)) {
				HomeActivityGroup.backAction = MainConstants.SZ_ACTION;
				finish();
				// overridePendingTransition(0, 0);
			} else {
				HomeActivityGroup.backAction = MainConstants.BACK_ACTION;
				qBackToActivity(HomeActivityGroup.class, null);
				startActivity_anim(11);
				// overridePendingTransition(0, 0);
			}
			break;
		case R.id.bt_longin:
			if (et_pnum_login.getText().toString().length() < 0
					&& et_psd_login.getText().toString().length() < 0) {
				showToast("请输入手机号和密码");
				break;
			} else if (et_pnum_login.getText().toString().length() < 0) {
				showToast("请输入手机号");
				break;
			} else if (et_psd_login.getText().toString().length() < 0) {
				showToast("请输入密码");
				break;
			} else if (!isPhoneNum(et_pnum_login.getText().toString())){
				showToast("请输入正确的手机号");
				break;
			}else if(et_psd_login.getText().toString().length()!=6){
				showToast("密码错误");
				break;
			}else{
				m.hideSoftInputFromWindow(et_pnum_login.getWindowToken(), 0);
				m.hideSoftInputFromWindow(et_pnum_login.getWindowToken(), 0);
				mobileNumber = et_pnum_login.getText().toString();
				userPassword = et_psd_login.getText().toString();
				// String
				// json="{\"userInfo.mobileNumber\":\""+mobileNumber+"\",\"userInfo.userPassword\":\""+userPassword+"\"}";

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("userInfo.mobileNumber",
						mobileNumber));
				params.add(new BasicNameValuePair("userInfo.userPassword",
						userPassword));
				// prepareRun();
				// HttpTask task = new HttpTask(handler,params,this);

				// task.setType(HttpTask.PSOT_VALUE);

				// task.setParams(params);
				// task.execute(MainConstants.HOST + "userInfo/user_login?"
				// + "userInfo.mobileNumber=" + mobileNumber + "&"
				// + "userInfo.userPassword=" + userPassword);

				// task.execute(MainConstants.HOST + "userInfo/user_login");
				if (CheckNetworkState()) {
					showProgress("登录中...");

					dataLoader.DisplayData(MainConstants.HOST
							+ "userInfo/user_login", params, handler,
							"",false);
				}

				// dataLoader.DisplayData(MainConstants.HOST +
				// "userInfo/user_login", params, handler);

			}
			break;
		case R.id.bt_wjmm_longin:
			m.hideSoftInputFromWindow(et_pnum_login.getWindowToken(), 0);
			m.hideSoftInputFromWindow(et_pnum_login.getWindowToken(), 0);
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("4006666377");
			builder.setPositiveButton("呼叫",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface arg0,
								int arg1) {
							call("4006666377");
						}
					});

			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface arg0,
								int arg1) {
						}
					});

			builder.create().show();
			break;
		}
	}

	@Override
	protected void onResume() {
		MobclickAgent.onResume(this);
		super.onResume();
	}

	@Override
	protected void onPause() {
		MobclickAgent.onPause(this);
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (dataReceiver != null) {
			unregisterReceiver(dataReceiver);
			dataReceiver = null;
		}

		// dataLoader.shutDown();
		m.hideSoftInputFromWindow(et_pnum_login.getWindowToken(), 0);
		m.hideSoftInputFromWindow(et_pnum_login.getWindowToken(), 0);

		isLogin = false;
	}

	// @Override
	// public boolean onKeyDown(int keyCode, KeyEvent event) {
	//
	// return super.onKeyDown(keyCode, event);
	// }

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			m.hideSoftInputFromWindow(et_pnum_login.getWindowToken(), 0);
			m.hideSoftInputFromWindow(et_pnum_login.getWindowToken(), 0);
			HomeActivityGroup.backAction = MainConstants.BACK_ACTION;
			if (startAction.equals(MainConstants.SZ_ACTION)) {
				HomeActivityGroup.backAction = MainConstants.SZ_ACTION;
				finish();
			} else {
				HomeActivityGroup.backAction = MainConstants.BACK_ACTION;
				qBackToActivity(HomeActivityGroup.class, null);
				startActivity_anim(11);
			}
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 注册广播
	 */
	private void register_Receiver() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(startAction);
		dataReceiver = new DataReceiver();
		registerReceiver(dataReceiver, filter);
	}

	// /**
	// * 启动服务
	// */
	// private void startService(int id) {
	// Intent intent = new Intent(this, DataService.class);
	// intent.setAction(startAction);
	// intent.putExtra("id", id);
	// startService(intent);
	// }
	//
	// /**
	// * 停止服务
	// */
	// private void stopService() {
	// Intent intent = new Intent(this, DataService.class);
	// intent.setAction(startAction);
	// stopService(intent);
	// }

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				// {"status":false,"errorMsg":null}
				// {"status":true,"userInfo":{"id":82739,"mobileNumber":"18638551072","userEmail":"hncaihongyu@163.com","userRealName":"蔡红玉"}}
				String result = msg.getData().getString("result");
				System.out.println(result);
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtils.isSuccess(result)) {// 判断返回数据中 status
															// 字段值是否为false
							JSONObject jobj = new JSONObject(result);
							JSONObject jo = jobj.optJSONObject("userInfo");
							// 保存用户信息
							SeveGRData(jo);
							finishProgress();
							// 启动服务
							// startService(Integer.parseInt(jo.optString("id")));
							// try {
							// if (startAction.equals(MainConstants.CX_ACTION))
							// {
							// // 请求数据
							// LoadData(jo);
							// } else if
							// (startAction.equals(MainConstants.HY_ACTION)) {
							// // 请求数据
							// LoadData(jo);
							// } else if
							// (startAction.equals(MainConstants.SZ_ACTION)) {
							// // 请求数据
							// LoadData(jo);
							// }
							//
							// } catch (Exception e) {
							// e.printStackTrace();
							// }

							Intent intent = new Intent(startAction);
							sendBroadcast(intent);

							isLogin = true;

						} else {
							isLogin = false;
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							showToast(StringUtils.geterrorMsg(result));
						}
					} catch (JSONException e) {
						isLogin = false;
						finishProgress();
						showToast("登录失败");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				isLogin = false;
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};

	class DataReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(MainConstants.CX_ACTION)) {
				// stopService();
				HomeActivityGroup.backAction = MainConstants.CX_ACTION;
				Intent i = new Intent(MainConstants.Data_ACTION);
				// i.putExtras(intent.getExtras());
				sendBroadcast(i);
				qBackToActivity(HomeActivityGroup.class, null);
				startActivity_anim(11);
			} else if (intent.getAction().equals(MainConstants.HY_ACTION)) {
				// stopService();
				HomeActivityGroup.backAction = MainConstants.HY_ACTION;
				Intent i = new Intent(MainConstants.Data_ACTION);
				// i.putExtras(intent.getExtras());
				sendBroadcast(i);
				qBackToActivity(HomeActivityGroup.class, null);
				startActivity_anim(11);

			} else if (intent.getAction().equals(MainConstants.SZ_ACTION)) {
				HomeActivityGroup.backAction = MainConstants.SZ_ACTION;
				Intent i = new Intent(MainConstants.Data_ACTION);
				// i.putExtras(intent.getExtras());
				sendBroadcast(i);
				qBackToActivity(HomeActivityGroup.class, null);
			}
		}

	}

	private void SeveGRData(JSONObject jo) {
		UserInfo user = new UserInfo();
		user.setId(jo.optString("id"));
		user.setMobileNumber(jo.optString("mobileNumber"));
		user.setUserEmail(jo.optString("userEmail"));
		user.setUserRealName(jo.optString("userRealName"));

		MainActivity.ID = Integer.parseInt(jo.optString("id"));

		// 将个人信息保存至本地
		SharedPreferences sp = getSharedPreferences("userinfo", MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		editor.putInt("id", Integer.parseInt(jo.optString("id")));
		editor.putString("mobileNumber", jo.optString("mobileNumber"));
		editor.putString("userEmail", jo.optString("userEmail"));
		editor.putString("userRealName", jo.optString("userRealName"));
		editor.commit();
	}

	/**
	 * 请求数据
	 * 
	 * @param jo
	 * @throws Exception
	 */
	// private void LoadData(JSONObject jo) throws Exception{
	//
	// // 请求客户卡片数据
	// List<NameValuePair> params1 = new ArrayList<NameValuePair>();
	// params1.add(new BasicNameValuePair("cardInfo.userId",
	// jo.optString("id")));
	// String result_cardInfo =
	// HttpUtil.requestStringForPost(MainConstants.HOST+
	// "cardInfo/query_card",params1,this);
	// CardInfoList cardInfoList = new CardInfoList(result_cardInfo);
	// List<CardInfo> carinfos = cardInfoList.getCarinfos();
	//
	//
	//
	//
	// // //消费记录
	// // List <NameValuePair> params2=new ArrayList<NameValuePair>();
	// // params2.add(new BasicNameValuePair("userConsumption.userId",
	// jo.optString("id")+""));
	// // String
	// consumption=HttpUtil.requestStringForPost(MainConstants.HOST+"consumption/query_consumption_record",
	// params2,this);
	// // ConsumptionList consumptionList=new ConsumptionList(consumption);
	// // List<Consumption> consumptions=consumptionList.getConsumptionList();
	// //
	// // //车险数据
	// // List <NameValuePair> params3=new ArrayList<NameValuePair>();
	// // params3.add(new BasicNameValuePair("vehicleInfo.userId",
	// jo.optString("id")));
	// // String
	// vehicleInfo=HttpUtil.requestStringForPost(MainConstants.HOST+"vehicleInfo/query_vehicle",params3,this);
	// //// System.out.println(vehicleInfo);
	// // VehicleInfoList vehicleInfoList=new VehicleInfoList(vehicleInfo);
	// // List<VehicleInfo> vehicleInfos=vehicleInfoList.getVehicleInfoList();
	//
	//
	// // if (carinfos != null&&consumptions!=null) {
	// // Intent intent = new Intent(startAction);
	// // Bundle bundle = new Bundle();
	// // bundle.putSerializable(CardInfoList.TAG,(Serializable) carinfos);
	// // bundle.putSerializable(ConsumptionList.TAG,(Serializable)
	// consumptions);
	// // bundle.putSerializable(VehicleInfoList.TAG,(Serializable)
	// vehicleInfos);
	// // intent.putExtras(bundle);
	// // sendBroadcast(intent);
	// // }
	// if (carinfos != null) {
	// Intent intent = new Intent(startAction);
	// Bundle bundle = new Bundle();
	// bundle.putSerializable(CardInfoList.TAG,(Serializable) carinfos);
	// intent.putExtras(bundle);
	// sendBroadcast(intent);
	// }
	// }
	// private void LoadData1(JSONObject jo) throws Exception{
	//
	//
	// //消费记录
	// List <NameValuePair> params2=new ArrayList<NameValuePair>();
	// params2.add(new BasicNameValuePair("userConsumption.userId",
	// jo.optString("id")+""));
	// String
	// consumption=HttpUtil.requestStringForPost(MainConstants.HOST+"consumption/query_consumption_record",
	// params2,this);
	// ConsumptionList consumptionList=new ConsumptionList(consumption);
	// List<Consumption> consumptions=consumptionList.getConsumptionList();
	//
	//
	// if (consumptions!=null) {
	// Intent intent = new Intent(startAction);
	// Bundle bundle = new Bundle();
	// bundle.putSerializable(ConsumptionList.TAG,(Serializable) consumptions);
	// intent.putExtras(bundle);
	// sendBroadcast(intent);
	// }
	// }
	//
	//
	// private void LoadData2(JSONObject jo) throws Exception{
	// //车险数据
	// List <NameValuePair> params3=new ArrayList<NameValuePair>();
	// params3.add(new BasicNameValuePair("vehicleInfo.userId",
	// jo.optString("id")));
	// String
	// vehicleInfo=HttpUtil.requestStringForPost(MainConstants.HOST+"vehicleInfo/query_vehicle",params3,this);
	// // System.out.println(vehicleInfo);
	// VehicleInfoList vehicleInfoList=new VehicleInfoList(vehicleInfo);
	// List<VehicleInfo> vehicleInfos=vehicleInfoList.getVehicleInfoList();
	//
	//
	// if (vehicleInfos != null) {
	// Intent intent = new Intent(startAction);
	// Bundle bundle = new Bundle();
	// bundle.putSerializable(VehicleInfoList.TAG,(Serializable) vehicleInfos);
	// intent.putExtras(bundle);
	// sendBroadcast(intent);
	// }
	// }
}
